//
//  MHHomePageViewController.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHHomePageViewController.h"
#import "MHNavigationController.h"
#import "MHProfileViewController.h"
#import "MHCircleHomeViewController.h"
#import "ConversationListViewController.h"
#import "MHDiscoverHomeViewController.h"
#import "MHDiscoverContainerViewController.h"
#import "UserHomePageController.h"
#import "MHWebViewController.h"
@interface MHHomePageViewController ()
/// viewModel

@property (nonatomic, readonly, strong) MHHomePageViewModel *viewModel;




@end

@implementation MHHomePageViewController

@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /// 初始化所有的子控制器
    [self _setupAllChildViewController];
    
    /// set delegate
    self.tabBarController.delegate = self;
    
}

#pragma mark - 初始化所有的子视图控制器
- (void)_setupAllChildViewController{
    NSArray *titlesArray = @[@"圈子", @"消息", @"发现", @"我"];
    NSArray *imageNamesArray = @[@"tabbar_circle_normal",
                                 @"tabbar_message_normal",
                                 @"tabbar_discover_normal",
                                 @"tabbar_bill_zhuanqian",
                                 @"tabbar_profile_normal"];
    NSArray *selectedImageNamesArray = @[@"tabbar_circle_sel",
                                         @"tabbar_message_sel",
                                         @"tabbar_discover_sel",
                                         @"tabbar_bill_zhuanqian",
                                         @"tabbar_profile_sel"];
    
    UINavigationController *circleNavController = ({
        MHCircleHomeViewController *profileViewController = [[MHCircleHomeViewController alloc] initWithViewModel:self.viewModel.circleViewModel];
        
        MHTabBarItemTagType tagType = MHTabBarItemTagTypeCircle;
        /// 配置
//        [self _configViewController:profileViewController imageName:imageNamesArray[tagType] selectedImageName:selectedImageNamesArray[tagType] title:titlesArray[tagType] itemTag:tagType];
        
        [[MHNavigationController alloc] initWithRootViewController:profileViewController];
    });
    
    UINavigationController *messageNavController = ({
        ConversationListViewController *profileViewController = [[ConversationListViewController alloc] initWithViewModel:self.viewModel.conversation];
        
        MHTabBarItemTagType tagType = MHTabBarItemTagTypeMessage;
        /// 配置
//        [self _configViewController:profileViewController imageName:imageNamesArray[tagType] selectedImageName:selectedImageNamesArray[tagType] title:titlesArray[tagType] itemTag:tagType];
        
        [[MHNavigationController alloc] initWithRootViewController:profileViewController];
    });
    
    /// 我的
    UINavigationController *discoverNavController = ({
//        MHDiscoverHomeViewController *discover = [[MHDiscoverHomeViewController alloc] initWithViewModel:self.viewModel.discoverViewModel];
        
        
        MHDiscoverContainerViewController *contaner = [[MHDiscoverContainerViewController alloc] initWithViewModel:self.viewModel.discoverContainerViewModel];
        
        MHTabBarItemTagType tagType = MHTabBarItemTagTypeDiscover;
        
        
        /// 配置
//        [self _configViewController:profileViewController imageName:imageNamesArray[tagType] selectedImageName:selectedImageNamesArray[tagType] title:titlesArray[tagType] itemTag:tagType];
        
        [[MHNavigationController alloc] initWithRootViewController:contaner];
    });
    
    
    
    UINavigationController *guideNavController = ({

        MHWebViewController *contaner = [[MHWebViewController alloc] initWithViewModel:self.viewModel.guideViewModel];
        MHTabBarItemTagType tagType = MHTabBarItemTagTypeGuide;
        [[MHNavigationController alloc] initWithRootViewController:contaner];
    });
    
    
    UINavigationController *profileNavigationController = ({
        UserHomePageController *profileViewController = [[UserHomePageController alloc] initWithViewModel:self.viewModel.profileViewModel];
        
        MHTabBarItemTagType tagType = MHTabBarItemTagTypeProfile;
        /// 配置
//        [self _configViewController:profileViewController imageName:imageNamesArray[tagType] selectedImageName:selectedImageNamesArray[tagType] title:titlesArray[tagType] itemTag:tagType];
        
        [[MHNavigationController alloc] initWithRootViewController:profileViewController];
    });
    
    
//    CYLTabBarController *tabBarController = [CYLTabBarController tabBarControllerWithViewControllers:@[ circleNavController, messageNavController, discoverNavController, profileNavigationController] tabBarItemsAttributes:[self tabBarItemsAttributesForController]];
    
//    [self customizeTabBarAppearance:tabBarController];
    
    [self customizeTabBarAppearance:self.tabBarController];
    /// 添加到tabBarController的子视图
//    self.tabBarController.imageInsets = UIEdgeInsetsMake(4.5, 0, -4.5, 0);
    self.tabBarController.tabBarItemsAttributes = [self tabBarItemsAttributesForController];
    self.tabBarController.viewControllers = @[circleNavController, messageNavController, discoverNavController,guideNavController, profileNavigationController];
    
    /// 配置栈底
    [MHSharedAppDelegate.navigationControllerStack pushNavigationController:circleNavController];
}

- (NSArray *)tabBarItemsAttributesForController {
    
    
//    NSArray *titlesArray = @[@"圈子", @"消息", @"发现", @"我"];
    NSArray *imageNamesArray = @[@"tabbar_circle_normal",
                                 @"tabbar_message_normal",
                                 @"tabbar_discover_normal",
                                 @"tabbar_bill_zhuanqian",
                                 @"tabbar_profile_normal"];
    NSArray *selectedImageNamesArray = @[@"tabbar_circle_sel",
                                         @"tabbar_message_sel",
                                         @"tabbar_discover_sel",
                                         @"tabbar_bill_zhuanqian",
                                         @"tabbar_profile_sel"];
    NSMutableArray * tabbarAttri = [NSMutableArray arrayWithCapacity:imageNamesArray.count];
    
    for (int i = 0; i< imageNamesArray.count; i++) {
        NSDictionary *firstTabBarItemsAttributes = @{
//                                                     CYLTabBarItemTitle : titlesArray[i],
                                                     CYLTabBarItemImage : [UIImage mh_imageAlwaysShowOriginalImageWithImageName:imageNamesArray[i]],  //,  /* NSString and UIImage are supported*/
                                                     CYLTabBarItemSelectedImage : [UIImage mh_imageAlwaysShowOriginalImageWithImageName:selectedImageNamesArray[i]],
                                                     };
        [tabbarAttri addObject:firstTabBarItemsAttributes];
    }
    return tabbarAttri;
}




- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
#warning CUSTOMIZE YOUR TABBAR APPEARANCE
    // Customize UITabBar height
    // 自定义 TabBar 高度
    tabBarController.tabBarHeight = CYL_IS_IPHONE_X ? 83 : 49;
    
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = MHColorFromHexString(@"#666666");
    normalAttrs[NSFontAttributeName] = MHRegularFont_10;
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = MHColorFromHexString(@"#FF0117");
    selectedAttrs[NSFontAttributeName] = MHRegularFont_10;
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // Set the dark color to selected tab (the dimmed background)
    // TabBarItem选中后的背景颜色
    // [self customizeTabBarSelectionIndicatorImage];
    
    // update TabBar when TabBarItem width did update
    // If your app need support UIDeviceOrientationLandscapeLeft or UIDeviceOrientationLandscapeRight，
    // remove the comment '//'
    // 如果你的App需要支持横竖屏，请使用该方法移除注释 '//'
    // [self updateTabBarCustomizationWhenTabBarItemWidthDidUpdate];
    
    // set the bar shadow image
    // This shadow image attribute is ignored if the tab bar does not also have a custom background image.So at least set somthing.
    
    
//    [[UITabBar appearance] setBackgroundImage:MHImageNamed(@"tabbar_circle_footer")];
//    [[UITabBar appearance] setTranslucent:YES];
    
    [[UITabBar appearance] setBackgroundImage:[UIImage new]];
    [[UITabBar appearance] setBackgroundColor:[UIColor whiteColor]];
    
    //FIXED: #196
//    UIImage *tabBarBackgroundImage = [UIImage imageNamed:@"tab_bar"];
//    UIImage *scanedTabBarBackgroundImage = [[self class] scaleImage:tabBarBackgroundImage toScale:1.0];
    //     [tabBarAppearance setBackgroundImage:scanedTabBarBackgroundImage];
    
    // remove the bar system shadow image
    // 去除 TabBar 自带的顶部阴影
    // iOS10 后 需要使用 `-[CYLTabBarController hideTabBadgeBackgroundSeparator]` 见 AppDelegate 类中的演示;
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
}


#pragma mark - 配置ViewController
- (void)_configViewController:(UIViewController *)viewController imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName title:(NSString *)title itemTag:(MHTabBarItemTagType)tagType {
    
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.image = image;
    viewController.tabBarItem.tag = tagType;
    
    UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
    selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.selectedImage = selectedImage;
    viewController.tabBarItem.title = title;
    
    NSDictionary *normalAttr = @{NSForegroundColorAttributeName:MHColorFromHexString(@"#929292"),
                                 NSFontAttributeName:MHRegularFont_10};
    NSDictionary *selectedAttr = @{NSForegroundColorAttributeName:MHColorFromHexString(@"#333333"),
                                   NSFontAttributeName:MHRegularFont_10};
    [viewController.tabBarItem setTitleTextAttributes:normalAttr forState:UIControlStateNormal];
    [viewController.tabBarItem setTitleTextAttributes:selectedAttr forState:UIControlStateSelected];
    
    [viewController.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, 0)];
    
//    //设配IPHONEX
//    CGFloat topOffset = (MH_APPLICATION_TAB_BAR_HEIGHT - selectedImage.size.height)/2;
//    CGFloat topOffsetIphoneX = (MH_APPLICATION_TAB_BAR_HEIGHT - selectedImage.size.height - zh_safeAreaHeight())/2;
//    if (!isIPhoneX()) {
//        [viewController.tabBarItem setImageInsets:UIEdgeInsetsMake(topOffset, 0, -topOffset, 0)];
//    }else
//    {
//        [viewController.tabBarItem setImageInsets:UIEdgeInsetsMake(topOffsetIphoneX, 0, - topOffsetIphoneX , 0)];
//    }
}


//#pragma mark - UITabBarControllerDelegate
//- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
//    /// 需要判断是否登录
//    if ([[self.viewModel.services client] isLogin]) return YES;
//
//    MHTabBarItemTagType tagType = viewController.tabBarItem.tag;
//
//    switch (tagType) {
//        case MHTabBarItemTagTypeHome:
//        case MHTabBarItemTagTypeConsign:
//            return YES;
//            break;
//        case MHTabBarItemTagTypeMessage:
//        case MHTabBarItemTagTypeProfile:
//        {
//            @weakify(self);
//            [[self.viewModel.services client] checkLogin:^{
//                @strongify(self);
//                self.tabBarController.selectedViewController = viewController;
//                [self tabBarController:tabBarController didSelectViewController:viewController];
//            } cancel:NULL];
//            return NO;
//        }
//            break;
//    }
//    return NO;
//}
//
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(MHNavigationController *)viewController
{
    
    if ([viewController.topViewController isKindOfClass:[MHDiscoverContainerViewController class]]) {
        [MHNotificationCenter postNotificationName:MHUpdateCurrentLocationNotification object:nil];
    }
//    NSLog(@"viewController   %@  %zd",viewController,viewController.tabBarItem.tag);
    [MHSharedAppDelegate.navigationControllerStack popNavigationController];
    [MHSharedAppDelegate.navigationControllerStack pushNavigationController:(UINavigationController *)viewController];
}

@end
